using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using JGSY.CourseManagement.Domain.Entities;
using JGSY.CourseManagement.Domain.Interfaces;
using JGSY.CourseManagement.Infrastructure.Data.EntityFramework;

namespace JGSY.CourseManagement.Infrastructure.Data.Repositories
{
    /// <summary>
    /// 用户会话仓储实现，使用SQLite数据库存储会话信息
    /// </summary>
    public class UserSessionRepository : IUserSessionRepository
    {
        private readonly SessionDbContext _dbContext;

        /// <summary>
        /// 初始化用户会话仓储
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public UserSessionRepository(SessionDbContext dbContext)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        }

        /// <summary>
        /// 添加新的用户会话
        /// </summary>
        public async Task<UserSession> AddAsync(UserSession session)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));

            // 设置默认会话属性
            session.ExpireTime = DateTime.UtcNow;
            session.CreationTime = DateTime.UtcNow;

            await _dbContext.UserSessions.AddAsync(session);
            await _dbContext.SaveChangesAsync();

            return session;
        }

        /// <summary>
        /// 获取当前用户会话
        /// </summary>
        public async Task<UserSession> GetAsync()
        {
            // 从全局变量获取当前会话ID
            var currentSessionId = GlobalValues.CurrentSessionId;
            if (string.IsNullOrEmpty(currentSessionId))
                return null;

            // 查询并返回有效的会话
            return await _dbContext.UserSessions
                .FirstOrDefaultAsync(s => s.SessionId == currentSessionId && s.IsActive);
        }
    }
}